const express = require('express');
const jwt = require('jsonwebtoken');
const {secret} = require('../../config/config');
const UserModel = require('../../models/UserModel');
const md5 = require('md5');

const router = express.Router();

router.post('/login', (req, res) => {
    UserModel.findOne({ ...req.body, password: md5(req.body.password) }).then((data) => {
        if (data) {
            req.session.username = data.username;
            req.session._id = data._id;
            let token = jwt.sign({ username: data.username, _id: data._id }, secret, {
                expiresIn: 60 * 60 * 24 * 7
            });
            res.json({
                code:'0',
                msg:'登录成功',
                data: token
            })
        } else {
            res.json({
                code:'1',
                msg:'用户名或密码错误',
                data:null
            })
        }
    }, (err) => {
        res.json({
            code: '2001',
            msg: '数据库读取失败',
            data: null,
        })
    });
})

router.post('/logout', (req, res) => {
    // 销毁session
    req.session.destroy(() => {
        res.render('success', { msg: "退出成功", url: "/login" });
    })
})
module.exports = router;
